package com.rainkaze.lifeharbor.tools.danmaku;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.google.android.material.slider.Slider;
import com.rainkaze.lifeharbor.R;
import com.rainkaze.lifeharbor.databinding.ActivityToolDanmakuBinding;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class DanmakuActivity extends AppCompatActivity {

    private ActivityToolDanmakuBinding binding;

    private int selectedTextColor = Color.WHITE;
    private int selectedBackgroundColor = Color.BLACK;
    private float selectedTextSizeSp = 100f;
    private float selectedSpeedFactor = 5f;

    // 预设颜色列表
    private final int[] presetColors = {
            Color.WHITE, Color.BLACK, Color.RED, Color.GREEN, Color.BLUE,
            Color.YELLOW, Color.CYAN, Color.MAGENTA, Color.parseColor("#FFA500"),
            Color.parseColor("#800080")
    };
    private final String[] presetColorNames = {
            "白", "黑", "红", "绿", "蓝", "黄", "青", "紫红", "橙", "紫"
    };

    private List<Button> textColorButtons = new ArrayList<>();
    private List<Button> backgroundColorButtons = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityToolDanmakuBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setupToolbar();
        setupColorPickers();
        setupSliders();
        setupPreview();
        setupStartButton();
    }

    private void setupToolbar() {
        setSupportActionBar(binding.toolbarDanmakuSettings);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    private void setupColorPickers() {
        // 文字颜色选择器
        for (int i = 0; i < presetColors.length; i++) {
            Button colorButton = createColorButton(presetColors[i]);
            final int color = presetColors[i];
            colorButton.setOnClickListener(v -> {
                selectedTextColor = color;
                updatePreview();
                highlightSelectedColorButton(textColorButtons, colorButton);
            });
            binding.layoutTextColors.addView(colorButton);
            textColorButtons.add(colorButton);
        }
        // 默认选中白色文字
        if (!textColorButtons.isEmpty()) {
            highlightSelectedColorButton(textColorButtons, textColorButtons.get(0));
        }

        // 背景颜色选择器
        for (int i = 0; i < presetColors.length; i++) {
            Button colorButton = createColorButton(presetColors[i]);
            final int color = presetColors[i];
            colorButton.setOnClickListener(v -> {
                selectedBackgroundColor = color;
                updatePreview();
                highlightSelectedColorButton(backgroundColorButtons, colorButton);
            });
            binding.layoutBackgroundColors.addView(colorButton);
            backgroundColorButtons.add(colorButton);
        }
        // 默认选中黑色背景
        if (backgroundColorButtons.size() > 1) {
            selectedBackgroundColor = presetColors[1];
            highlightSelectedColorButton(backgroundColorButtons, backgroundColorButtons.get(1));
        }
        updatePreview();
    }

    private Button createColorButton(int color) {
        Button button = new Button(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                dpToPx(40), dpToPx(40)
        );
        params.setMargins(dpToPx(4), dpToPx(4), dpToPx(4), dpToPx(4));
        button.setLayoutParams(params);
        button.setBackgroundColor(color);
        return button;
    }
    private void highlightSelectedColorButton(List<Button> buttons, Button selectedButton) {
        for (Button btn : buttons) {
            btn.setAlpha(0.7f);
        }
        selectedButton.setAlpha(1.0f);
    }

    private boolean isColorDark(int color) {
        double darkness = 1 - (0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color)) / 255;
        return darkness >= 0.5;
    }


    private void setupSliders() {
        // 文字大小
        binding.sliderTextSize.addOnChangeListener((slider, value, fromUser) -> {
            selectedTextSizeSp = value;
            binding.textViewTextSizeValue.setText(String.format(Locale.getDefault(), "%.0fsp", value));
            updatePreview();
        });
        // 初始化显示
        binding.textViewTextSizeValue.setText(String.format(Locale.getDefault(), "%.0fsp", binding.sliderTextSize.getValue()));

        // 滚动速度
        binding.sliderScrollSpeed.addOnChangeListener((slider, value, fromUser) -> {
            selectedSpeedFactor = value;
            binding.textViewScrollSpeedValue.setText(String.format(Locale.getDefault(), "速度: %.0f", value));
        });
        // 初始化显示
        binding.textViewScrollSpeedValue.setText(String.format(Locale.getDefault(), "速度: %.0f", binding.sliderScrollSpeed.getValue()));
    }

    private void setupPreview() {
        binding.editTextDanmakuText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                updatePreview();
            }
            @Override
            public void afterTextChanged(Editable s) {}
        });
        // 初始预览
        updatePreview();
        binding.textViewPreviewDanmaku.setSelected(true);
    }

    private void updatePreview() {
        String text = binding.editTextDanmakuText.getText().toString();
        if (TextUtils.isEmpty(text)) {
            binding.textViewPreviewDanmaku.setText("预览文字");
        } else {
            binding.textViewPreviewDanmaku.setText(text);
        }
        binding.textViewPreviewDanmaku.setTextColor(selectedTextColor);
        binding.textViewPreviewDanmaku.setBackgroundColor(selectedBackgroundColor);
        binding.textViewPreviewDanmaku.setTextSize(TypedValue.COMPLEX_UNIT_SP, selectedTextSizeSp / 3); // 预览字号适当缩小
    }

    private void setupStartButton() {
        binding.buttonStartDanmaku.setOnClickListener(v -> {
            String danmakuText = binding.editTextDanmakuText.getText().toString().trim();
            if (TextUtils.isEmpty(danmakuText)) {
                Toast.makeText(this, "请输入弹幕文字！", Toast.LENGTH_SHORT).show();
                return;
            }

            Intent intent = new Intent(DanmakuActivity.this, DanmakuDisplayActivity.class);
            intent.putExtra(DanmakuDisplayActivity.EXTRA_TEXT, danmakuText);
            intent.putExtra(DanmakuDisplayActivity.EXTRA_TEXT_COLOR, selectedTextColor);
            intent.putExtra(DanmakuDisplayActivity.EXTRA_BACKGROUND_COLOR, selectedBackgroundColor);
            intent.putExtra(DanmakuDisplayActivity.EXTRA_TEXT_SIZE_SP, selectedTextSizeSp);
            intent.putExtra(DanmakuDisplayActivity.EXTRA_SPEED_FACTOR, selectedSpeedFactor);
            startActivity(intent);
        });
    }

    private int dpToPx(int dp) {
        return (int) (dp * getResources().getDisplayMetrics().density);
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}